<template>
  <view class="edit-profile-container">
    <view class="form-container">
      <u-form :model="formData" ref="formRef" label-width="160">
        <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">基本信息</view>
          
          <u-form-item label="真实姓名" prop="realName">
            <u-input 
              v-model="formData.realName" 
              placeholder="请输入真实姓名"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
          
       
          
        <!--  <u-form-item label="出生日期" prop="birthday">
            <view class="picker-wrapper" @click="showDatePicker = true">
              <text :class="{ 'placeholder': !formData.birthday }">
                {{ formData.birthday || '请选择出生日期' }}
              </text>
              <u-icon name="arrow-right" size="16" color="#ccc"></u-icon>
            </view>
          </u-form-item> -->
          
          <u-form-item label="所在城市" prop="city">
            <u-input 
              v-model="formData.city" 
              placeholder="请输入所在城市"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
          
          <u-form-item label="邮箱" prop="email">
            <u-input 
              v-model="formData.email" 
              placeholder="请输入邮箱"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
        </view>
        
        <!-- 教育背景 -->
        <view class="form-section">
          <view class="section-title">教育背景</view>
          
          <u-form-item label="学历" prop="education">
            <u-input 
              v-model="formData.education" 
              placeholder="如：本科/硕士/博士"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
          
          <u-form-item label="学校" prop="school">
            <u-input 
              v-model="formData.school" 
              placeholder="请输入学校名称"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
        </view>
        
        <!-- 教学信息（仅教员） -->
        <view class="form-section" v-if="isTeacher">
          <view class="section-title">教学信息</view>
          
          <u-form-item label="擅长科目" prop="subjects">
            <u-input 
              v-model="formData.subjects" 
              placeholder="如：数学、英语、物理"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
          
          <u-form-item label="教学经验(年)" prop="experienceYears">
            <u-input 
              v-model.number="formData.experienceYears" 
              type="number"
              placeholder="请输入教学经验年数"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
          
          <u-form-item label="时薪(元/小时)" prop="hourlyRate">
            <u-input 
              v-model.number="formData.hourlyRate" 
              type="digit"
              placeholder="请输入时薪"
              :border="true"
              border-color="#e4e7ed"
            ></u-input>
          </u-form-item>
        </view>
        
        <!-- 个人简介 -->
        <view class="form-section">
          <view class="section-title">个人简介</view>
          
          <u-form-item label="个人简介" prop="intro">
            <u-input 
              v-model="formData.intro" 
              type="textarea"
              placeholder="请介绍一下自己..."
              :border="true"
              border-color="#e4e7ed"
              :maxlength="500"
              :show-word-limit="true"
              :custom-style="{
                minHeight: '200rpx'
              }"
            ></u-input>
          </u-form-item>
        </view>
      </u-form>
      
      <!-- 保存按钮 -->
      <view class="button-section">
        <u-button 
          type="primary" 
          :loading="loading"
          @click="handleSave"
          :custom-style="{
            borderRadius: '50rpx',
            height: '88rpx',
            backgroundColor: '#3cc51f',
            borderColor: '#3cc51f'
          }"
        >
          保存
        </u-button>
      </view>
    </view>
    
    <!-- 日期选择器 -->
    <u-picker
      v-model="showDatePicker"
      mode="time"
      :params="dateParams"
      @confirm="onDateConfirm"
    ></u-picker>
  </view>
</template>

<script>
import { getUserProfile, updateProfile } from '@/api/user'
import { isTeacher } from '@/utils/auth'

export default {
  data() {
    return {
      loading: false,
      showDatePicker: false,
      formData: {
        realName: '',
        gender: 'MALE',
        birthday: '',
        city: '',
        email: '',
        education: '',
        school: '',
        subjects: '',
        experienceYears: null,
        hourlyRate: null,
        intro: ''
      },
      dateParams: {
        year: true,
        month: true,
        day: true,
        timestamp: true
      }
    }
  },
  
  computed: {
    isTeacher() {
      return isTeacher()
    }
  },
  
  onLoad() {
    this.loadProfile()
  },
  
  methods: {
    async loadProfile() {
      try {
        uni.showLoading({ title: '加载中...' })
        const response = await getUserProfile()
        
        if (response.code === 200 && response.data) {
          const data = response.data
          
          this.formData = {
            realName: data.realName || '',
            gender: data.gender || 'MALE',
            birthday: data.birthday || '',
            city: data.city || '',
            email: data.email || '',
            education: data.education || '',
            school: data.school || '',
            subjects: data.subjects || '',
            experienceYears: data.experienceYears || null,
            hourlyRate: data.hourlyRate || null,
            intro: data.intro || ''
          }
        }
      } catch (error) {
        console.error('加载个人信息失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    onDateConfirm(e) {
      // 格式化日期为 YYYY-MM-DD
      const timestamp = e.timestamp
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      this.formData.birthday = `${year}-${month}-${day}`
    },
    
    validateForm() {
      if (this.formData.email && !this.isValidEmail(this.formData.email)) {
        uni.showToast({
          title: '邮箱格式不正确',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.realName && this.formData.realName.length > 50) {
        uni.showToast({
          title: '真实姓名长度不能超过50个字符',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.intro && this.formData.intro.length > 500) {
        uni.showToast({
          title: '个人简介长度不能超过500个字符',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    isValidEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return emailRegex.test(email)
    },
    
    async handleSave() {
      if (!this.validateForm()) {
        return
      }
      
      this.loading = true
      
      try {
        // 准备提交的数据，过滤掉空值
        const submitData = {}
        for (const key in this.formData) {
          const value = this.formData[key]
          if (value !== '' && value !== null && value !== undefined) {
            submitData[key] = value
          }
        }
        
        await updateProfile(submitData)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-profile-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 40rpx;
}

.form-container {
  padding: 20rpx;
}

.form-section {
  background: white;
  border-radius: 20rpx;
  padding: 20rpx 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    margin-bottom: 20rpx;
  }
}

.picker-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  
  text {
    font-size: 28rpx;
    color: #333;
    
    &.placeholder {
      color: #999;
    }
  }
}

.button-section {
  padding: 40rpx 30rpx;
}
</style>

